package org.jeecg.modules.basedata.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.BaseFloor;
import org.jeecg.entity.basedata.BaseFloorInfo;
import org.jeecg.modules.basedata.service.IBaseFloorInfoService;
import org.jeecg.modules.basedata.service.IBaseFloorService;
import org.jeecg.modules.basedata.service.IBaseProjectService;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.vo.basedata.BaseFloorPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 楼宇
 * @Author: jeecg-boot
 * @Date:   2019-07-02
 * @Version: V1.0
 */
@RestController
@RequestMapping("/b/basedata/baseFloor")
@Slf4j
public class BaseFloorController {
	@Autowired
	private IBaseFloorService baseFloorService;
	@Autowired
	private IBaseProjectService baseProjectService;

	 /**
	  * 分页列表查询
	 * @param baseFloor
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<BaseFloorPage>> queryPageList(BaseFloorPage baseFloor,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		Result<IPage<BaseFloorPage>> result = new Result<IPage<BaseFloorPage>>();
		try{
			Page<BaseFloorPage> pageList = new Page<BaseFloorPage>(pageNo, pageSize);
			if(StringUtils.isNotEmpty(baseFloor.getProjectId())){
				pageList = baseFloorService.listByParams(pageList,baseFloor);
			}
			result.setSuccess(true);
			result.setResult(pageList);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}




	 @GetMapping(value = "/getRoomCount")
	 public Result<Integer> getRoomCount(BaseFloor baseFloor) {
		 Integer count = 0;
		 try{
			 count= baseFloorService.getRoomCount(baseFloor.getId());
			 return Result.ok(count);
		 }catch (Exception e ){
			 log.error(e.getMessage());
			 return Result.error("系统繁忙!");
		 }
	 }

	 /**
	  * 批量删除判断楼宇下是否绑定房间
	  * @param
	  * @return
	  */
	 @GetMapping(value = "/getRoomCounts")
	 public Result<Integer> getRoomCounts(@RequestParam(name="ids",required=true) String ids) {
		 Integer count = 0;
		 try{
			 count= baseFloorService.getRoomCounts(ids.split(","));
			 return Result.ok(count);
		 }catch (Exception e ){
			 e.printStackTrace();
			 return Result.error("系统繁忙!");
		 }
	 }

	/**
	 * 依据多个项目获取楼宇
	 */
	 @GetMapping(value = "/queryFloorLists")
	 public Result queryFloorLists(@RequestParam(name = "projectIds") String projectIds){
	 	if (StringUtils.isBlank(projectIds)) return Result.error("参数不可为空!");
		List<String> projectIdList = Arrays.asList(projectIds.split(","));
		List<BaseFloor> floorList = baseFloorService.list(Wrappers.<BaseFloor>query().lambda().in(BaseFloor::getProjectId,projectIdList).eq(BaseFloor::getDelFlag,0)
		 	.orderByAsc(BaseFloor::getProjectId).orderByAsc(BaseFloor::getName).last("limit 10000"));
	 	return Result.ok(floorList);
	 }


	 /**
	  * 依据项目获取楼宇
	  */
	 @RequestMapping("getFloorList")
	 public Result<List<BaseFloor>> getFloorList(@RequestBody JSONObject projectId){
		 String asString = projectId.getString("projectId");
		 Result<List<BaseFloor>> result = new Result<>();
		 List<BaseFloor> baseFloors = baseFloorService.queryFloorList(asString);
		 result.setResult(baseFloors);
		 result.setSuccess(true);
		 return result;
	 }
	 /**
	  *   添加
	 * @param baseFloorPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<BaseFloor> add(@RequestBody BaseFloorPage baseFloorPage) {
		Result<BaseFloor> result = new Result<BaseFloor>();
		try {
			BaseFloor baseFloor = new BaseFloor();
			BeanUtils.copyProperties(baseFloorPage, baseFloor);

			BaseFloorInfo baseFloorInfo = new BaseFloorInfo();
			BeanUtils.copyProperties(baseFloorPage, baseFloorInfo);
			
			baseFloorService.saveMain(baseFloor, baseFloorInfo);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param baseFloorPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<BaseFloor> edit(@RequestBody BaseFloorPage baseFloorPage) {
		Result<BaseFloor> result = new Result<BaseFloor>();
		BaseFloor baseFloor = new BaseFloor();
		BeanUtils.copyProperties(baseFloorPage, baseFloor);
        BaseFloorInfo baseFloorInfo = new BaseFloorInfo();
        BeanUtils.copyProperties(baseFloorPage, baseFloorInfo);
		BaseFloor baseFloorEntity = baseFloorService.getById(baseFloor.getId());
		if(baseFloorEntity==null) {
			result.error500("未找到对应实体");
		}else {
			baseFloorService.updateById(baseFloor);
            baseFloorService.updateMain(baseFloor, baseFloorInfo);
			result.success("修改成功!");
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<BaseFloor> delete(@RequestParam(name="id",required=true) String id) {
		Result<BaseFloor> result = new Result<BaseFloor>();
		BaseFloor baseFloor = baseFloorService.getById(id);
		if(baseFloor==null) {
			result.error500("未找到对应实体");
		}else {
			baseFloorService.delMain(id);
			result.success("删除成功!");
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<BaseFloor> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<BaseFloor> result = new Result<BaseFloor>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.baseFloorService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<BaseFloorPage> queryById(@RequestParam(name="id",required=true) String id) {
		Result<BaseFloorPage> result = new Result<BaseFloorPage>();
        BaseFloorPage baseFloorPage = baseFloorService.selectByMainId(id);
		if(baseFloorPage==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(baseFloorPage);
			result.setSuccess(true);
		}
		return result;
	}
    

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response, BaseFloorPage baseFloor) {
		LoginUser user = SsoUtil.getLoginUser();
		Page<BaseFloorPage> page = new Page<BaseFloorPage>(1, baseFloorService.list().size());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<BaseFloorPage> pageList = new ArrayList<BaseFloorPage>();
        Page<BaseFloorPage> baseFloorList = baseFloorService.listByParams(page, baseFloor);
        for (BaseFloorPage b : baseFloorList.getRecords()) {
            BaseFloorPage vo = new BaseFloorPage();
            BeanUtils.copyProperties(b, vo);
            pageList.add(vo);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "楼宇列表");
        mv.addObject(NormalExcelConstants.CLASS, BaseFloorPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("楼宇列表数据", "导出人:" + user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response,String projectId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setNeedSave(false);
            try {
				int successNum = 0;
				int failureNum = 0;
				int row = 1;
				StringBuilder failureMsg = new StringBuilder();
                List<BaseFloorPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BaseFloorPage.class, params);
				ArrayList<BaseFloor> floorList = Lists.newArrayList();
				if (list != null && list.size() > 0) {
                    List<String> collect = list.stream().map(BaseFloorPage::getName).distinct().collect(Collectors.toList());
                    if (collect.size() < list.size()){
                    	return Result.error("文件中存在相同的楼宇名称");
					}
                    for (BaseFloorPage floor : list) {
						if (StringUtils.isEmpty(floor.getProjectName())){
							failureMsg.append("<br/>第").append(row).append("行：请输入项目名称; ");
							failureNum++;
							row++;
							continue;
				       	}else {
							String projectName = baseFloorService.queryProjectName(projectId);
							if (!projectName.equals(floor.getProjectName())){
								failureMsg.append("<br/>第").append(row).append("行：请输入与选择项目一致的名称 ");
								failureNum++;
								row++;
								continue;
							}
							floor.setProjectId(projectId);
						}
						if (StringUtils.isEmpty(floor.getName())){
							failureMsg.append("<br/>第").append(row).append("行：请输入楼宇名称 ");
							failureNum++;
							row++;
							continue;
						}if (StringUtils.isEmpty(floor.getCode())){
							failureMsg.append("<br/>第").append(row).append("行：请输入楼宇编号 ");
							failureNum++;
							row++;
							continue;
						}

						BaseFloor po = new BaseFloor();
						BeanUtils.copyProperties(floor, po);
					    floorList.add(po);
					}
					baseFloorService.saveBatch(floorList);
					if (failureNum > 0) {
						failureMsg.insert(0, "，失败 " + failureNum + " ，导入信息如下：");
					}
					return Result.ok("已成功导入 " + floorList.size() + " 条信息" + failureMsg );
				}
				return Result.error("导入楼宇基础信息失败！Excel数据为空");
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("文件导入失败:"+e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }
}
